import React, { useEffect, useRef, useState } from "react";

interface IProp {
  item: { id: number; content: string; type: string };
  onTimeout: (id: number) => void;
}

export default function ToastItem({ item, onTimeout }: IProp) {
  const self = useRef<HTMLDivElement | null>(null);
  const [pos, setPos] = useState(0);
  useEffect(() => {
    setTimeout(() => {
      // 移除自己
      onTimeout(item.id);
    }, 2000);

    // 获取到我的上一个兄弟元素
    let prev = self.current?.previousElementSibling as HTMLDivElement;
    // 两个弹出之间的距离
    let offset = 20;
    // 上一个兄弟元素距离body顶部的距离
    let top = prev?.offsetTop || 0;
    let h = prev?.offsetHeight || 0;
    let pos = top + h + offset; //算出我的位置
    setPos(pos);
  }, []);
  return (
    <div ref={self} className="toast-item" style={{ top: pos }}>
      {item.id},{item.content}
    </div>
  );
}
